import { changePoint } from "../event/mouseEvent";
import BaseElement from './base';
import getInstance from './ctx';
import DrawArrow from './arrow';

/**
 * 元素周围的小圆圈，具有扩展功能
 */
class EditTagElement {
	constructor(props) {
		const radius = 8; // 设置半径大小
		this.hide = true; //是否隐藏元素
		this.x = props.x;
		this.y = props.y;
		this.width = 2 * radius;
		this.height = 2 * radius;
		this.type = 'EditTagElement';
		this.color = "00f"
		this.r = radius;
		this.ArrowList = [];
		this.canvas = getInstance(); // 绘图实例
		this.canvas.elementList.push(this)
	}

	render(x, y) {
		this.canvas.ctx.beginPath();
		this.canvas.ctx.moveTo(this.x + this.r, this.y);
		this.canvas.ctx.arc(this.x, this.y, this.r, 2 * Math.PI, 0, true);
		this.canvas.ctx.fillStyle = '#fff';
		this.canvas.ctx.fill();
		this.canvas.ctx.closePath();
		this.canvas.ctx.stroke();

		if (x && y && this.canvas.ctx.isPointInPath(x, y)) {
			if (this.canvas.isdruging) {
				this.canvas.ctx.fillStyle = "#fef1fe";
			}
			this.canvas.hoverElement = this;
			this.hover && this.hover(x, y);
		} else if (!this.canvas.hoverElement) {
			changePoint("default");
		}
	}

	hover() {
		console.log("EditTagElement hover");
		if (this.canvas.isArrowing && this.canvas.ArrowElement && (this.canvas.ArrowElement.startElement !== this)) {
			this.canvas.ctx.fillStyle = '#f00';
			this.canvas.ctx.fill();
		}
		this.canvas.isdruging = false;
		this.canvas.isArrowing = true;
		changePoint("crosshair");
	}
	onmousedown() {
		// 是否开始箭头
		if (this.canvas.isArrowing) {
			console.log("准备绘制箭头");
			// 计算当前点在父元素的位置
			let position = 0;
			this.canvas.hoverElement.parent.editTagList.forEach((tag, index) => {
				if (this.canvas.hoverElement.x === tag.x && this.canvas.hoverElement.y === tag.y) {
					position = index;
				}
			});
			// 开始绘图
			let arrow = new DrawArrow({
				fromX: this.canvas.hoverElement.x,
				fromY: this.canvas.hoverElement.y,
				toX: this.canvas.hoverElement.x,
				toY: this.canvas.hoverElement.y,
			});
			this.canvas.hoverElement.ArrowList.push(arrow); // 此时this.canvas.hoverElement 指的是 editTag
			arrow.direction = position;
			arrow.startElement = this.canvas.hoverElement;
			this.canvas.ArrowElement = arrow;
			this.canvas.elementList.push(arrow);
		}
	}
	onmouseup() {
		// 是否是当前节点
		if (this.canvas.isArrowing && this.canvas.ArrowElement && (this.canvas.ArrowElement.startElement !== this)) {
			console.log("！！！找到目标点", this.canvas.ArrowElement.id)
			this.canvas.ArrowElement.toX = this.x;
			this.canvas.ArrowElement.toY = this.y;
			this.canvas.ArrowElement.endElement = this;
			this.ArrowList.push(this.canvas.ArrowElement);
		}
	}
	drug(x, y) {
		console.log("EditTagElement is drug");
		this.ArrowList.forEach((arrow) => {
			if (arrow.startElement === this) {
				arrow.drug(x, y);
			} else if (arrow.endElement === this) {
				arrow.drug(0, 0, x, y);
			} else {
				console.log("都不是")
			}

		});
	}

}

export default EditTagElement;